﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
using SerialPortHelperLib;
using System.Threading;
using XChipTool.Enties;
using System.Configuration;
using XChip_Common;
using BinAnalysisHelp;

namespace XChipTool
{
    public partial class XChip_Lite_Scene_Switch : DevExpress.XtraEditors.XtraUserControl
    {
        public SerialPort sPortTemp;
        private bool isRead = false;
        private bool isWrite = false;
        private addressregisterManager aBll;
        private List<addressregister> XChipScene_Switch;
        private List<addressregister> XChipAe;
        List<string> listfiltration = new List<string> {  };
        List<string> listFiltration = new List<string> { "AE_WIDTH", "AE_HEIGHT", "AE_WIN_WIDTH_X", "AE_WIN_HEIGHT_Y", "AE_WIN_WIDTH", "AE_WIN_HEIGHT" };
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;
        public XChip_Lite_Scene_Switch()
        {
            InitializeComponent();
        }
        public XChip_Lite_Scene_Switch(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            sPortTemp = _sPortTemp;
            aBll = _aBll;
            XChipScene_Switch = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "Scene" || c.Classify == "Common"));
            XChipAe = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "ae" || c.Classify == "Common"));
            InitializeComponent();
        }
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            isRead = true;
            //gain_switch0.Text = (GetSceneRegister("gain_switch0_0") << 8 | GetSceneRegister("gain_switch0_1")).ToString("X2");
            //gain_switch1.Text = (GetSceneRegister("gain_switch1_0") << 8 | GetSceneRegister("gain_switch1_1")).ToString("X2");
            //gain_switch2.Text = (GetSceneRegister("gain_switch2_0") << 8 | GetSceneRegister("gain_switch2_1")).ToString("X2");
            //gain_switch3.Text = (GetSceneRegister("gain_switch3_0") << 8 | GetSceneRegister("gain_switch3_1")).ToString("X2");
            //avg_switch.Text = (GetSceneRegister("avg_switch0") << 8 | GetSceneRegister("avg_switch1")).ToString("X2");
            //area_avg_switch_high.Text = (GetSceneRegister("area_avg_switch_h0") << 8 | GetSceneRegister("area_avg_switch_h1")).ToString("X2");
            //area_avg_switch_low.Text = (GetSceneRegister("area_avg_switch_l0") << 8 | GetSceneRegister("area_avg_switch_l1")).ToString("X2");
            string nameType = string.Empty;
            List<string> NameList = new List<string>();

            for (int i = 0; i < XChipScene_Switch.Count; i++)
            {
                if (XChipScene_Switch[i].NameType.Contains("IQSwitch_night_val_ratio"))
                {

                }
                var type = AppHelper.NameTypeToString(XChipScene_Switch[i].NameType);
                if (NameList.Exists(c => c.ToLower().Contains(type)))
                {
                    continue;
                }
                ////加上单选框的_en
                //if (XChipAwb[i].ControlType == "1")
                //{
                //    type = XChipAwb[i].NameType;
                //}
                if (XChipScene_Switch[i].NameType == "IQSwitch_night_val_ratio" || XChipScene_Switch[i].NameType == "IQSwitch_night_val_num")
                {
                    type = XChipScene_Switch[i].NameType;
                }
                var col = Controls_Find(type);

                foreach (var item in col)
                {
                    if (item is TextEdit)
                    {

                        var nList = XChipScene_Switch.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        if (nList.Count == 0)
                        {
                            nList = XChipScene_Switch.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        }
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
                        }
                        else
                        {
                            string Val = string.Empty;
                            //这里默认为是有多个寄存器  一个文本框的情况进行处理
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
                            {
                                if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_h")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_h")).Address, 16), sPortTemp).ToString("X2");
                                }
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m1")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m1")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
                            {
                                Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address, 16), sPortTemp).ToString("X2");
                            }
                            if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                            {
                                if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                                else
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Last(c => c.NameType.ToLower().Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                }
                            }
                            if (string.IsNullOrEmpty(Val))
                            {
                                nList = XChipScene_Switch.Where(c => c.NameType.ToLower() == (item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                                if (nList.Count() == 1)
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                }
                            }
                            item.Text = Val;
                        }
                    }
                    else if (item is CheckEdit)
                    {
                        var nList = XChipScene_Switch.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                        if (nList.Count == 1)
                        {
                            var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                            (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val) == 0;
                        }
                    }


                }

                NameList.Add(type);
            }
            string Vals = string.Empty;
            Vals += SerialSend.ReadRegister(Convert.ToUInt32(XChipScene_Switch.Find(c => c.NameType==("avg_switch_h")).Address, 16), sPortTemp).ToString("X2");
            Vals += SerialSend.ReadRegister(Convert.ToUInt32(XChipScene_Switch.Find(c => c.NameType==("avg_switch_l")).Address, 16), sPortTemp).ToString("X2");
            avg_switch.Text = Vals;
            simpleButton1_Click(null, null);
            isRead = true;
            simpleButton3_Click(null, null);
            GetAEWin();//获取ae windows部分

            if ((GetAERegister("Scene_Switch_En") & 0x12) == 0x12)
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Checked;
                checkedListBoxControl1.Items[1].Enabled = true;
            }
            else
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Unchecked;
                checkedListBoxControl1.Items[1].Enabled = false;
                AE_radiomode.Enabled = false;
            }
            if ((GetAERegister("Debug_En") & 0x02) == 0x00)
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Checked;
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)
                {
                    AE_radiomode.Enabled = true;
                }
            }
            else
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Unchecked;
                AE_radiomode.Enabled = false;
            }
            isRead = false;
        }
        private Control[] Controls_Find(string str)
        {
            //var t =   this.Controls.Find(type, true);
            List<Control> listc = new List<Control>();
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            for (int i = 0; i < fieldInfo.Length; i++)
            {
                if (fieldInfo[i].Name.ToLower().Contains(str.ToLower()))
                {
                    listc.AddRange(this.Controls.Find(fieldInfo[i].Name, true));
                    break;
                }
            }
            return listc.ToArray();
        }
        private void GetAEWin()
        {
            //if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)
            //{
            //    switch (AE_radiomode.SelectedIndex)
            //    {
            //        case 0:
            //            labelControl10.Text = "Day Mode";
            //            for (int i = 0; i < 64; i++)
            //            {
            //                var nTemp = GetAERegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Day");//SerialSend.ReadRegister((ulong)(0x80140000 | (0x5b + i)), sPortTemp).ToString("X2");
            //                SetAEWin(i, nTemp);
            //            }
            //            break;
            //        case 1:
            //            labelControl10.Text = "Night Mode";
            //            for (int i = 0; i < 64; i++)
            //            {
            //                var nTemp = GetAERegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Night");//SerialSend.ReadRegister((ulong)(0x80140000 | (0x5b + i)), sPortTemp).ToString("X2");
            //                SetAEWin(i, nTemp);
            //            }
            //            break;
            //        case 2:
            //            labelControl10.Text = "Midnight Mode";
            //            for (int i = 0; i < 64; i++)
            //            {
            //                var nTemp = GetAERegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Midnight");//SerialSend.ReadRegister((ulong)(0x80140000 | (0x5b + i)), sPortTemp).ToString("X2");
            //                SetAEWin(i, nTemp);
            //            }
            //            break;
            //        default:
            //            break;
            //    }
            //}
            //else
            //{
            //    for (int i = 0; i < 64; i++)
            //    {
            //        var nTemp = GetAERegister($"AE_WEIGHT_{(i + 1).ToString("D2")}");//SerialSend.ReadRegister((ulong)(0x80140000 | (0x5b + i)), sPortTemp).ToString("X2");
            //        SetAEWin(i, nTemp);
            //    }
            //}

            //这个测光窗口只读写20000c78开始的这组寄存器
            for (int i = 0; i < 64; i++)
            {
                var nTemp = GetAERegister($"AE_WEIGHT_{(i + 1).ToString("D2")}_Day");
                SetAEWin(i, nTemp);
            }





            //long nMask = 0;
            //nMask = GetAERegister("Scene_Switch_En");

            //List<string> NameList = new List<string>();

            //for (int i = 0; i < XChipAe.Count; i++)
            //{

            //    var type = AppHelper.NameTypeToString(XChipAe[i].NameType);
            //    if (NameList.Exists(c => c.ToLower().Contains(type)))
            //    {
            //        continue;
            //    }
            //    //if (XChipAe[i].NameType.Contains("AE_WIDTH"))
            //    //{

            //    //}
            //    ////加上单选框的_en
            //    //if (XChipAe[i].ControlType == "1")
            //    //{
            //    //    type = XChipAe[i].NameType;
            //    //}
            //    //if (type.Contains("AE_WIN_WIDTH".ToLower()))
            //    //{

            //    //}
            //    try
            //    {
            //        var col = Controls_Find(type);
            //        foreach (var item in col)
            //        {
            //            if (item is TextEdit)
            //            {
            //                var nList = XChipAe.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();

            //                if (nList.Count == 1)
            //                {
            //                    string Val = "";


            //                    Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");

            //                    item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
            //                }
            //                else
            //                {   //处理AE_TARGET_JUDGE_TAB

            //                    string Val = string.Empty;

            //                    //这里默认为是有多个寄存器  一个文本框的情况进行处理
            //                    if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
            //                    {
            //                        Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address, 16), sPortTemp).ToString("X2");
            //                    }
            //                    if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
            //                    {
            //                        Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address, 16), sPortTemp).ToString("X2");
            //                    }
            //                    if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
            //                    {
            //                        if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
            //                        {
            //                            Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
            //                        }
            //                        else
            //                        {
            //                            Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Last(c => c.NameType.ToLower().Contains("_l")).Address, 16), sPortTemp).ToString("X2");
            //                        }
            //                    }


            //                    if (listFiltration.Exists(c => c == item.Name.ToString()))
            //                    {
            //                        item.Text = Convert.ToInt32(Val, 16).ToString();
            //                    }
            //                    else
            //                    {
            //                        item.Text = Val;
            //                    }

            //                }
            //            }
            //            else if (item is CheckEdit)
            //            {
            //                var nList = XChipAe.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
            //                if (nList.Count == 1)
            //                {
            //                    string Val = "";
            //                    if (IsUsbOpen)
            //                    {
            //                        uint pVule = 0x0;
            //                        bool isbool;
            //                        if (IntPtr.Size == 8)
            //                        {
            //                            isbool = XChipUSB.UsbRegisterRead64(Convert.ToUInt32(nList[0].Address, 16), ref pVule, false);
            //                        }
            //                        else
            //                        {
            //                            isbool = XChipUSB.UsbRegisterRead86(Convert.ToUInt32(nList[0].Address, 16), ref pVule, false);
            //                        }
            //                        var addrstr = Convert.ToUInt32(Convert.ToUInt32(nList[0].Address, 16));
            //                        SerialSend.Sendser("R:0x" + addrstr.ToString("X2"), pVule.ToString("X2"));
            //                        Val = pVule.ToString("X");

            //                    }
            //                    else
            //                    {
            //                        Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
            //                    }
            //                    (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val) == 0;
            //                }
            //            }


            //        }

            //        //ae_win_width\ae_win_height 重复名称太多 这里不过滤 数据进行强匹配
            //        if (type.ToLower().Contains("ae_win_width") || type.ToLower().Contains("ae_win_height"))
            //        {
            //            continue;
            //        }
            //        NameList.Add(type);
            //    }
            //    catch (Exception)
            //    {
            //        continue;
            //    }
            //}
        }
       
        private void SetAEWin(int i, long nTemp)
        {
            foreach (Control item in groupControl2.Controls)
            {
                if (item is TextEdit)
                {
                    if (item.Name == $"AE_WEIGHT_{(i + 1).ToString("D2")}")
                    {
                        item.Text = (nTemp).ToString("X2");
                    }
                }
                if (item is CheckEdit)
                {
                    if (item.Name == $"AE_WT_{i}_EN")
                    {
                        if ((nTemp & 0x80) == 0x80)
                        {
                            ((CheckEdit)item).Checked = true;
                        }
                        else
                        {
                            ((CheckEdit)item).Checked = false;
                        }
                    }
                }
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            //long m_nDayMode;
            isRead = true;
            //long nMask = (SerialSend.ReadRegister((Convert.ToUInt32(XChipAe.Where(c => c.NameType == "Scene_Mode").First().Address, 16)), sPortTemp) & 0x3);
            long nMask = (GetAERegister("Scene_Mode") & 0x3);
            if (nMask == 0)
            {
                AE_radiomode.SelectedIndex = 0;
            }
            else if (nMask == 1)
            {
                AE_radiomode.SelectedIndex = 1;
            }
            else if (nMask == 2)
            {
                AE_radiomode.SelectedIndex = 2;
            }
            //Scene_Switch_En
            //if ((SerialSend.ReadRegister((Convert.ToUInt32(XChipAe.Where(c => c.NameType == "Scene_Switch_En").First().Address, 16)), sPortTemp) & 0x04) == 0x04)
            if ((GetAERegister("Scene_Switch_En") & 0x12) == 0x12)
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Checked;
                checkedListBoxControl1.Items[1].Enabled = true;
            }
            else
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Unchecked;
                checkedListBoxControl1.Items[1].Enabled = false;
                AE_radiomode.Enabled = false;
            }
            //Debug_En
            //if ((SerialSend.ReadRegister((Convert.ToUInt32(XChipAe.Where(c => c.NameType == "Debug_En").First().Address, 16)), sPortTemp) & 0x02) == 0x00)
            if ((GetAERegister("Debug_En") & 0x02) == 0x00)
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Checked;
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)
                {
                    AE_radiomode.Enabled = true;
                }
            }
            else
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Unchecked;
                AE_radiomode.Enabled = false;
            }           
            isRead = false;
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }

            List<string> listfiltration = new List<string> { "s_nGlobalCurAvg", "s_n_Cur_gain", "nCurAreaAvg" };
            List<string> NameList = new List<string>();
            for (int i = 0; i < XChipScene_Switch.Count; i++)
            {
                var type = AppHelper.NameTypeToString(XChipScene_Switch[i].NameType);
                //加上单选框的_en
                if (XChipScene_Switch[i].ControlType == "1")
                {
                    type = XChipScene_Switch[i].NameType;
                }
                var col = this.Controls.Find(type, true);
                foreach (var item in col)
                {
                    if (NameList.Exists(c => c.Contains(type)))
                    {
                        continue;
                    }
                    else
                    {

                        //过滤掉指定寄存器
                        if (!listfiltration.Exists(c => c.Contains(item.Name.ToString())))
                        {
                            continue;
                        }
                        if (item is TextEdit)
                        {

                            var nList = XChipScene_Switch.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                            if (nList.Count == 1)
                            {
                                var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                item.Text = BitsHelp.GetBitsToUint(nList[0].Bits, nList[0].Hex, Val).ToString("X");
                            }
                            else
                            {
                                var listsum = nList.Select(c => c.Address).Distinct().ToList();
                                string Val = string.Empty;

                                //这里默认为是有多个寄存器  一个文本框的情况进行处理
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_h")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_h")).Address, 16), sPortTemp).ToString("X2");
                                }
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_m1")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m1")).Address, 16), sPortTemp).ToString("X2");
                                }
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_m0")))
                                {
                                    Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Contains("_m0")).Address, 16), sPortTemp).ToString("X2");
                                }
                                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                                {
                                    if (nList.Exists(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")))
                                    {
                                        Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Find(c => c.NameType.ToLower().Substring(c.NameType.Length - 2).Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                    }
                                    else
                                    {
                                        Val += SerialSend.ReadRegister(Convert.ToUInt32(nList.Last(c => c.NameType.ToLower().Contains("_l")).Address, 16), sPortTemp).ToString("X2");
                                    }
                                }
                                if (string.IsNullOrEmpty(Val))
                                {
                                    nList = XChipScene_Switch.Where(c => c.NameType.ToLower() == (item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                                    if (nList.Count() == 1)
                                    {
                                        Val += SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                    }
                                }
                                item.Text = Val;
                            }
                        }
                        else if (item is CheckEdit)
                        {
                            var nList = XChipScene_Switch.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                            if (nList.Count == 1)
                            {
                                var Val = SerialSend.ReadRegister(Convert.ToUInt32(nList[0].Address, 16), sPortTemp).ToString("X");
                                (item as CheckEdit).Checked = BitsHelp.GetBitsCheckedToBool(nList[0].Bits, nList[0].Hex, Val) == 0;
                            }
                        }


                    }
                }
                NameList.Add(type);
            }

        }
        private void checkedListBoxControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
         
        }
        private void AE_radiomode_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var aeradio = sender as DevExpress.XtraEditors.RadioGroup;
            if (aeradio.SelectedIndex == 0)
            {
                SetAeRegister("Scene_Mode", 0x00);
            }
            else if (aeradio.SelectedIndex == 1)
            {
                SetAeRegister("Scene_Mode", 0x01);
            }
            else if (aeradio.SelectedIndex == 2)
            {
                SetAeRegister("Scene_Mode", 0x02);
            }
            GetAEWin();
            simpleButton2_Click(null, null);
        }
        #region 封装寄存器读写
        private long GetSceneRegister(string nameType)
        {
            if (XChipScene_Switch.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
                return SerialSend.ReadRegister(Convert.ToUInt32(XChipScene_Switch.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, 16), sPortTemp);
            else { DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1; }
        }
        private void SetSceneRegister(string nameType, ulong add)
        {
            if (isRead) return;
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            if (IsUsbOpen)
            {
                if (null != BinHelp.usbList && IsUsbOpen)
                {
                    uint pVule = 0x0;
                    var isbool = false;
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, XChipHelp.XChipCADJ.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, add.ToString("X"), chang, kuang);
                }
            }
            else if (m_open)
            {

            }
            else
            {
                if (null != BinHelp.lspList&& XChipScene_Switch.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
                { //编写Bin更新数据
                    var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                    BinHelp.SetBinUpdateData(ref BinHelp.BinList, XChipScene_Switch.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, add.ToString("X"), (uint)temp);
                }

            }
            if (XChipScene_Switch.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
            {
                SerialSend.WriteRegister(Convert.ToUInt32(XChipScene_Switch.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, 16), add, sPortTemp);
            }
           
        }
        private void SetSceneRegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (isRead) return; //判断是否在读，读的时候不进行写     
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)//串口检测
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("串口未打开");
                return;
            }
           

            if (IsUsbOpen)
            {
                if (null != BinHelp.usbList)
                {
                    uint pVule = 0x0;
                    var isbool = false;
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));


                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), chang, kuang);
                }
            }
            else if (m_open)
            {

            }
            else
            {
                if (!sPortTemp.IsOpen)
                {
                    DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                    return;
                }
                if (null != BinHelp.lspList)
                { //编写Bin更新数据
                    var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                    BinHelp.SetBinUpdateData(ref BinHelp.BinList, model.Address, add.ToString("X"), (uint)temp);
                }
            }
            SerialSend.WriteRegister(Convert.ToUInt32(model.Address, 16), add, sPortTemp);
            
        }
        private void SetAeRegister(string nameType, ulong add)
        {
            if (isRead) return;
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            if (IsUsbOpen)
            {
                if (null != BinHelp.usbList && IsUsbOpen)
                {
                    uint pVule = 0x0;
                    var isbool = false;
                    if (IntPtr.Size == 8)
                    {
                        isbool = XChipUSB.UsbRegisterRead64(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    else
                    {
                        isbool = XChipUSB.UsbRegisterRead86(BinHelp.CurrentSize, ref pVule, true);
                        SerialSend.Sendser("R:0x" + (BinHelp.CurrentSize).ToString("X2"), pVule.ToString("X2"));
                    }
                    var chang = (int)(pVule >> 16); // 使用右移16位操作来获取高16位  
                    var kuang = (int)(pVule & 0xFFFF); // 使用位与操作来获取低16位  

                    BinHelp.SstBinUsbUpdateData(ref BinHelp.BinList, XChipHelp.XChipCADJ.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, add.ToString("X"), chang, kuang);
                }
            }
            else if (m_open)
            {

            }
            else
            {
                if (null != BinHelp.lspList && XChipAe.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
                { //编写Bin更新数据
                    var temp = SerialSend.ReadRegister(BinHelp.BootSettingIdx, sPortTemp);
                    BinHelp.SetBinUpdateData(ref BinHelp.BinList, XChipAe.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, add.ToString("X"), (uint)temp);
                }

            }
            if (XChipAe.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
            {
                SerialSend.WriteRegister(Convert.ToUInt32(XChipAe.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, 16), add, sPortTemp);
            }
           
        }
        private long GetAERegister(string nameType)
        {
            if (XChipAe.Where(c => c.NameType.ToLower() == nameType.ToLower()).Count() > 0)
                return SerialSend.ReadRegister(Convert.ToUInt32(XChipAe.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address, 16), sPortTemp);
            else { DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1; }
        }


        #endregion

        private void checkedListBoxControl1_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (isRead) return;
            ////Scence Switch En 
            //var nTemp1 = SerialSend.ReadRegister((Convert.ToUInt32(XChipAe.Where(c => c.NameType == "Scene_Switch_En").First().Address, 16)), sPortTemp);
            //// Debug en
            //var nTemp2 = SerialSend.ReadRegister((Convert.ToUInt32(XChipAe.Where(c => c.NameType == "Debug_En").First().Address, 16)), sPortTemp);
            //Scence Switch En 
            var nTemp1 = GetAERegister("Scene_Switch_En");
            // Debug en
            var nTemp2 = GetAERegister("Debug_En");
            if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
            {
                SetAeRegister("Scene_Switch_En", 0x12);
                checkedListBoxControl1.Items[1].Enabled = true;
                if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
                {
                    AE_radiomode.Enabled = true;
                }
            }
            else  //S不勾选
            {
                SetAeRegister("Scene_Switch_En", 0x00);
                checkedListBoxControl1.Items[1].Enabled = false;
                AE_radiomode.Enabled = false;
            }


            if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
            {
                SetAeRegister("Debug_En", (ulong)(nTemp2 & 0xfd));
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
                {
                    AE_radiomode.Enabled = true;
                }
            }
            else//D不勾选
            {
                SetAeRegister("Debug_En", (ulong)(nTemp2 | 0x02));
                AE_radiomode.Enabled = false;
            }
        }

        private void AE_WT_EN1_CheckedChanged(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            if (isRead) return;
            var tempCheck = sender as CheckEdit;            
            //simpleButton1_Click(null, null);//获取当前场景
            string tempName = string.Empty;
            int index = int.Parse(tempCheck.Name.Replace("AE_WT_", "").Replace("_EN", ""));
            ulong value;
            if (tempCheck.Checked == true) {
                switch (AE_radiomode.SelectedIndex)
                {
                    case 0:
                        tempName = $"AE_WEIGHT_{(index - 1).ToString("X2")}_Day";
                        value = (ulong)GetAERegister(tempName) | 0x80;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    case 1:
                        tempName = $"AE_WEIGHT_{(index - 1).ToString("X2")}_Night";
                        value = (ulong)GetAERegister(tempName) | 0x80;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    case 2:
                        tempName = $"AE_WEIGHT_{(index - 1).ToString("X2")}_Midnight";
                        value = (ulong)GetAERegister(tempName) | 0x80;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    default:
                        break;                           
                }
            }
            if (tempCheck.Checked == false)
            {
                switch (AE_radiomode.SelectedIndex)
                {
                    case 0:
                        tempName = $"AE_WEIGHT_{(index - 1).ToString("X2")}_Day";
                        value = (ulong)GetAERegister(tempName) & 0x7f;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    case 1:
                        tempName = $"AE_WEIGHT_{(index - 1).ToString("X2")}_Night";
                        value = (ulong)GetAERegister(tempName) &0x7f;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    case 2:
                        tempName = $"AE_WEIGHT_{(index - 1).ToString("X2")}_Midnight";
                        value = (ulong)GetAERegister(tempName) &0x7f;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    default:
                        break;    
                }
            }
        }
        //ae window赋值
        private void SetAETxt(int index, ulong value)
        {
           
            foreach (Control item in groupControl2.Controls)
            {
                if (item is TextEdit)
                {
                    if ($"AE_WEIGHT_{(index + 1).ToString("D2")}" == item.Name)
                        item.Text = (value).ToString("X2");
                    //item.Text = (value ).ToString("X2");
                }
            }            
        }

        private void textEdit1_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (string.IsNullOrEmpty(gain_switch0.Text)) return;
            //var temp = Convert.ToUInt32(gain_switch0.Text, 16);
            //var high = temp >> 8;
            //var low = temp & 0xff;
            //SetSceneRegister("gain_switch0_0", high);
            //SetSceneRegister("gain_switch0_1", low);
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写          
            var txt = sender as TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;

            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
        }

        private void textEdit2_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (string.IsNullOrEmpty(gain_switch1.Text)) return;
            //var temp = Convert.ToUInt32(gain_switch1.Text, 16);
            //var high = temp >> 8;
            //var low = temp & 0xff;
            //SetSceneRegister("gain_switch1_0", high);
            //SetSceneRegister("gain_switch1_1", low);
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写          
            var txt = sender as TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;

            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
        }

        private void textEdit3_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (string.IsNullOrEmpty(gain_switch2.Text)) return;
            //var temp = Convert.ToUInt32(gain_switch2.Text, 16);
            //var high = temp >> 8;
            //var low = temp & 0xff;
            //SetSceneRegister("gain_switch2_0", high);
            //SetSceneRegister("gain_switch2_1", low);
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写          
            var txt = sender as TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;

            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
        }

        private void textEdit4_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (string.IsNullOrEmpty(gain_switch3.Text)) return;
            //var temp = Convert.ToUInt32(gain_switch3.Text, 16);
            //var high = temp >> 8;
            //var low = temp & 0xff;
            //SetSceneRegister("gain_switch3_0", high);
            //SetSceneRegister("gain_switch3_1", low);
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写          
            var txt = sender as TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;

            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
        }

        private void textEdit5_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (string.IsNullOrEmpty(avg_switch.Text)) return;
            //var temp = Convert.ToUInt32(avg_switch.Text, 16);
            //var high = temp >> 8;
            //var low = temp & 0xff;
            //SetSceneRegister("avg_switch0", high);
            //SetSceneRegister("avg_switch1", low);
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写          
            var txt = sender as TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;

            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
        }

        private void textEdit6_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (string.IsNullOrEmpty(area_avg_switch_h.Text)) return;
            //var temp = Convert.ToUInt32(area_avg_switch_h.Text, 16);
            //var high = temp >> 8;
            //var low = temp & 0xff;
            //SetSceneRegister("area_avg_switch_h0", high);
            //SetSceneRegister("area_avg_switch_h1", low);
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写          
            var txt = sender as TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;

            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
        }

        private void textEdit7_Leave(object sender, EventArgs e)
        {
            //if (isWrite) return;
            //if (string.IsNullOrEmpty(area_avg_switch_l.Text)) return;
            //var temp = Convert.ToUInt32(area_avg_switch_l.Text, 16);
            //var high = temp >> 8;
            //var low = temp & 0xff;
            //SetSceneRegister("area_avg_switch_l0", high);
            //SetSceneRegister("area_avg_switch_l1", low);
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写          
            var txt = sender as TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;

            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
        }

        private void textEdit1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                textEdit1_Leave(sender, null);
            }
        }

        private void textEdit2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                textEdit2_Leave(sender, null);
            }
        }

        private void textEdit3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                textEdit3_Leave(sender, null);
            }
        }

        private void textEdit4_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                textEdit4_Leave(sender, null);
            }
        }

        private void textEdit5_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                textEdit5_Leave(sender, null);
            }
        }

        private void textEdit6_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                textEdit6_Leave(sender, null);
            }
        }

        private void textEdit7_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                textEdit7_Leave(sender, null);
            }
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            //string str = "       设置场景切换所需的判定条件，其中：\r\n       Day_mode为当前增益 ＜ gain_switch [0] 且所选测光窗口亮度 ＞ area_avg_switch_h时；\r\n       Night_mode为gain_switch [1] ＜ 当前增益 ＜ gain_switch [2] 且所选测光窗口亮度 ＞ area_avg_switch_l时；\r\n       Midnight_mode为当前增益 ＞ gain_switch [3] 且全局亮度 ＜ avg_switch时。\r\n       更多详见《调试工具用户手册》。";
            Thread thread = new Thread(threadPro);
            thread.Start();
        }
        private void threadPro()

        {

            MethodInvoker methodInvoker = new MethodInvoker(ShowFormB);

            BeginInvoke(methodInvoker);

        }

        private void ShowFormB()

        {
            //string str = "\t      \t 设置场景切换所需的判定条件，其中：\r\n"
            //     + "\t      \t Day_mode为cur_gain ＜ gain_switch [0] 且area_avg ＞ area_avg_switch_h时；\r\n"
            //     + "\t      \t Night_mode为gain_switch [1] ＜ cur_gain ＜ gain_switch [2] 且area_avg ＞ area_avg_switch_l时；\r\n"
            //     + "\t      \t Midnight_mode为cur_gain ＞ gain_switch [3] 且global_avg ＜ avg_switch时。\r\n"
            //     + "\t      \t 更多详见《调试工具用户手册》。\r\n";
            string str = "";
            XChip_OptimizationTips ot = new XChip_OptimizationTips("SCENE调优Tips", str);
            ot.StartPosition = FormStartPosition.CenterScreen;
            //ot.ShowDialog();
            ot.Show();

        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            //SerialSend.isDebug = false;
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型 
            sfd.Filter = "配置文件（*.txt）|*.txt";

            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            sfd.FileName = "IQ_Setting_Scene_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                var Pe_dal = new parameter_exportManager();
                if (null != Pe_dal)
                {
                    WaitBefore.Start("参数导出", "正在加载中", 60);
                    var tempList = Pe_dal.GetListToExport().Where(c => c.Module == "scene_condition" ||
                    c.Module == "Area Weight" || 
                    c.Module.Contains("avg_weight 0x8014005b")).OrderBy(c => c.SortNum).ToList();
                    #region 判断是否需要用白天的数据
                    var Pe_patch_dal = new parameter_export_patchManager();
                    var patchList = Pe_patch_dal.GetList();
                    var conditionList = tempList.Select(c => c.ConditionAddr).Distinct();
                    foreach (var item in conditionList)
                    {
                        if (SerialSend.ReadRegister(Convert.ToUInt32(item, 16), sPortTemp) == 0)
                        {
                            patchList.RemoveAll(c => c.ConditionAddr == item);
                        }
                    }
                    #endregion
                    var sb = XChipHelp.ReadParameterExportExpand(tempList, "80", patchList, sPortTemp);
                    System.IO.File.WriteAllText(sfd.FileName, sb.ToString());

                }
                WaitBefore.Close();
                DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
            }
        }

        private void simpleButton2_MouseEnter(object sender, EventArgs e)
        {
            isWrite = true;
        }

        private void simpleButton2_MouseLeave(object sender, EventArgs e)
        {
            isWrite = false;
        }

        private void XChip_Scene_Switch_Load(object sender, EventArgs e)
        {
            Task.Run(() => {
                this.Invoke((EventHandler)delegate {
                    for (int i = 0; i < XChipScene_Switch.Count; i++)
                    {

                        var type = AppHelper.NameTypeToString(XChipScene_Switch[i].NameType);
                        try
                        {
                            var col = this.Controls.Find(type, true);


                            foreach (var item in col)
                            {
                                if (item is TextEdit)
                                {
                                    //声明一个SuerToolTip
                                    DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                                    //声明一个ToolTipTitleItem,保存标题
                                    DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                                    String tooltips = "";

                                    if (!string.IsNullOrEmpty(XChipScene_Switch[i].Bit_Wide))
                                    {
                                        tooltips += $"位宽={XChipScene_Switch[i].Bit_Wide}";
                                    }
                                    if (!string.IsNullOrEmpty(XChipScene_Switch[i].Bit_Accuracy))
                                    {
                                        tooltips += $"|精度={XChipScene_Switch[i].Bit_Accuracy}";
                                    }
                                    //设置标题文字
                                    toolTipTitleItem.Text = tooltips;
                                    //把标题添加到SuerToolTip
                                    graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                                    //指定控件的SuperTip
                                    ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                                    //正则判断
                                    ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                                    ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipScene_Switch[i].Bits, XChipScene_Switch[i].Bit_Wide, XChipScene_Switch.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());
                                }
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                });
            });
        }

        private void AE_WT_15_EN_CheckedChanged(object sender, EventArgs e)
        {
            if (!sPortTemp.IsOpen && !IsUsbOpen && !m_open)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("可用端口未打开");
                return;
            }
            if (isRead) return;
            var tempCheck = sender as CheckEdit;
            //simpleButton1_Click(null, null);//获取当前场景
            string tempName = string.Empty;
            int index = int.Parse(tempCheck.Name.Replace("AE_WT_", "").Replace("_EN", ""));
            ulong value;
            tempName = $"AE_WEIGHT_{(index + 1).ToString("D2")}";
            value = (ulong)GetAERegister(tempName) | 0x80;
            SetAETxt(index, value);
            SetAeRegister(tempName, value);
            if (tempCheck.Checked == true)
            {
                switch (AE_radiomode.SelectedIndex)
                {
                    case 0:
                        tempName = $"AE_WEIGHT_{(index + 1).ToString("D2")}_Day";
                        value = (ulong)GetAERegister(tempName) | 0x80;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    case 1:
                        tempName = $"AE_WEIGHT_{(index + 1).ToString("D2")}_Night";
                        value = (ulong)GetAERegister(tempName) | 0x80;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    case 2:
                        tempName = $"AE_WEIGHT_{(index + 1).ToString("D2")}_Midnight";
                        value = (ulong)GetAERegister(tempName) | 0x80;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    default:
                        break;
                }
            }
            if (tempCheck.Checked == false)
            {
                switch (AE_radiomode.SelectedIndex)
                {
                    case 0:
                        tempName = $"AE_WEIGHT_{(index + 1).ToString("D2")}_Day";
                        value = (ulong)GetAERegister(tempName) & 0x7f;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    case 1:
                        tempName = $"AE_WEIGHT_{(index + 1).ToString("D2")}_Night";
                        value = (ulong)GetAERegister(tempName) & 0x7f;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    case 2:
                        tempName = $"AE_WEIGHT_{(index + 1).ToString("D2")}_Midnight";
                        value = (ulong)GetAERegister(tempName) & 0x7f;
                        SetAETxt(index, value);
                        SetAeRegister(tempName, value);
                        break;
                    default:
                        break;
                }
            }
        }

        private void s_n_Cur_gain_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;

            if (isRead) return;
            var txt = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == (txt.Name + "_h" ).ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == (txt.Name + "_h" ).ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == (txt.Name + "_m1").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == (txt.Name + "_m1").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == (txt.Name + "_m0").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == (txt.Name + "_m0").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == (txt.Name + "_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
        }

        private void IQSwitch_night_val_num_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写          
            var txt = sender as TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;

            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
        }

        private void nCurAreaAvg_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            if (isRead) return; //判断是否在读，读的时候不进行写          
            var txt = sender as TextEdit;
            if (string.IsNullOrEmpty(txt.Text)) return;

            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_h").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == ($"{txt.Name}_l").ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                SetSceneRegister(model, Val);
            }
        }

        private void IQSwitch_night_adjust_en_CheckedChanged(object sender, EventArgs e)
        {
            var chk = sender as CheckEdit;
            if (isRead) return;
            if (XChipScene_Switch.Exists(c => c.NameType.ToLower() == (chk.Name).ToLower()))
            {
                var model = XChipScene_Switch.Find(c => c.NameType.ToLower() == (chk.Name).ToLower());
                var Add = SerialSend.ReadRegister(Convert.ToUInt32(model.Address, 16), sPortTemp);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), chk.Checked);
                SetSceneRegister(model, Val);
            }
        }

        private void IQSwitch_night_val_ratio_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                IQSwitch_night_val_num_Leave(sender, null);
            }
        }

        private void nCurAreaAvg_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                nCurAreaAvg_Leave(sender, null);
            }
        }

        private void s_n_Cur_gain_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                s_n_Cur_gain_Leave(sender, null);
            }
        }
    }
}
